<script setup lang="ts">
import { ref, toRaw } from "vue";
import { onLoad, onUnload } from "@dcloudio/uni-app";
import { items_api, del_api } from "@/package/my/api/tour_info";
import { EV_CONTACTS } from "@/constant/event";
import { strReplaceByLen } from "@/utils/string";
import { Router } from "@/utils/router";
import { Toast } from "@/utils/toast";

import ListEmpty from "@/components/list/empty.vue";
import PageSticky from "@/components/page/sticky.vue";
import FormCheckbox from "@/components/form/checkbox.vue";
import ListContactsItem from "./components/list-contacts-item.vue";
import FormButton from "@/components/form/button.vue";
import PopupModal from "@/components/popup/modal.vue";

onLoad((options) => {
  reloadList();

  // 选择模式
  if (options?.mode === "select") {
    uni.setNavigationBarTitle({
      title: options?.type === "2" ? "选择出行人" : "选择联系人",
    });
    listMode.value = "select";
    if (options?.id) {
      selectList.value = options.id.split(",").map((i: string) => Number(i));
    }
    selectType.value = options?.type || ""; // 选择类型；1：联系人；2：出行人
    tempData.selectMax = Number(options?.num || 1);
  }

  uni.$on(EV_CONTACTS, contactsCallback);
});
onUnload(() => uni.$off(EV_CONTACTS, contactsCallback));

const listMode = ref(""); // 列表模式；select：选择模式

const listData = ref<any[]>([]);
const listStatus = ref<"more" | "loading" | "noMore">("more");
const reloadList = () => {
  return items_api().then((resp) => {
    listData.value = resp.items.map((i) => {
      return {
        ...i,
        phone_str: strReplaceByLen(i.phone),
        cardNo_str:
          i.identity_type === 1 ? strReplaceByLen(i.cardNo, 6) : i.cardNo,
      };
    });
    listStatus.value = "noMore";
  });
};
const contactsClick = (index: number) => {
  listMode.value === "select"
    ? selectClick(index)
    : editClick(listData.value[index].id);
};
const editClick = (id?: string) => {
  Router.navigateTo(`/package/my/pages/contacts/edit?id=${id || ""}`);
};
const delClick = (id: string) => {
  popupModal.value?.show({ content: "是否确定删除该信息？" }, () => {
    Toast.showLoading();
    del_api({ id })
      .then(() => {
        Toast.hideLoading();
        // showToast("删除成功");
        reloadList();
      })
      .catch(() => Toast.hideLoading());
  });
};

const selectList = ref<number[]>([]);
const selectType = ref("");
const selectClick = (index: number) => {
  const item = listData.value[index];
  if (selectType.value === "1") {
    selectList.value = [item.id];
    uni.$emit(EV_CONTACTS, {
      type: "select",
      data: { type: selectType.value, data: [toRaw(item)] },
    });
    Router.navigateBack();
  } else {
    const _selectList = selectList.value;
    _selectList.includes(item.id)
      ? _selectList.splice(_selectList.indexOf(item.id), 1)
      : tempData.selectMax === _selectList.length
      ? Toast.show(`仅需填写${tempData.selectMax}位出行人信息`)
      : _selectList.push(item.id);
  }
};
const confirmClick = () => {
  const _listData = toRaw(listData.value);
  const _selectList = toRaw(selectList.value);
  if (_selectList.length === 0) return Toast.show(`请选择出行人`);
  uni.$emit(EV_CONTACTS, {
    type: "select",
    data: {
      type: selectType.value,
      data: _listData.filter((i) => _selectList.includes(i.id)),
    },
  });
  Router.navigateBack();
};

const contactsCallback = (e: { type: "edit" | "del" }) => {
  console.info(`触发事件：${EV_CONTACTS}`, e);
  (e.type === "edit" || e.type === "del") && reloadList();
};

const popupModal = ref<InstanceType<typeof PopupModal>>();
const tempData = { selectMax: 1 };
</script>

<template>
  <view
    class="list-no-data"
    v-if="listData.length === 0 && listStatus === 'noMore'"
  >
    <ListEmpty text="您没有添加常用联系人～～" />
  </view>

  <template v-else>
    <PageSticky background="#f9f9f9">
      <view class="list-title">出行人</view>

      <view class="list-add" v-if="selectType === '2'" @click="editClick('')">
        <image
          class="list-add-icon"
          src="@/package/my/static/contacts-add.png"
        />
        添加
      </view>
    </PageSticky>

    <view class="list-data">
      <uni-swipe-action>
        <view class="list-data-action" v-for="(i, d) of listData" :key="i.id">
          <uni-swipe-action-item>
            <view class="list-data-item" @click="contactsClick(d)">
              <view class="list-data-checkbox" v-if="listMode === 'select'">
                <FormCheckbox :modelValue="selectList.includes(i.id)" />
              </view>
              <view style="flex-grow: 1; min-width: 0">
                <ListContactsItem :info="i">
                  <image
                    class="list-data-edit"
                    src="@/package/my/static/address-edit.png"
                    @click.stop="editClick(i.id)"
                  />
                </ListContactsItem>
              </view>
            </view>
            <template v-slot:right>
              <view class="list-data-del" @click="delClick(i.id)">删除</view>
            </template>
          </uni-swipe-action-item>
        </view>
      </uni-swipe-action>
    </view>
  </template>

  <view class="list-fixed">
    <view v-if="selectType === '2'" @click="confirmClick">
      <FormButton :disabled="selectList.length === 0">确认</FormButton>
    </view>
    <view v-else @click="editClick('')">
      <FormButton>+ 添加</FormButton>
    </view>
  </view>

  <PopupModal ref="popupModal" />
</template>

<style lang="scss">
.list-title {
  display: flex;
  align-items: center;
  height: 100rpx;
  padding-left: 30rpx;
  font-size: 30rpx;
  color: #333333;
  line-height: 44rpx;
  font-weight: bold;
}

.list-add {
  position: absolute;
  top: 16rpx;
  right: 30rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 168rpx;
  height: 68rpx;
  font-size: 28rpx;
  color: #2d2d2d;
  line-height: 40rpx;
  border-radius: 44rpx;
  background-color: #ffffff;

  .list-add-icon {
    width: 28rpx;
    height: 28rpx;
    margin-right: 8rpx;
  }
}

.list-data {
  // padding-top: 30rpx;
  padding-bottom: 120rpx;

  .list-data-action {
    margin-bottom: 20rpx;
  }

  .list-data-item {
    display: flex;
    align-items: center;
    padding-left: 30rpx;
    padding-right: 30rpx;
  }

  .list-data-checkbox {
    flex-shrink: 0;
    margin-right: 20rpx;
  }

  .list-data-edit {
    flex-shrink: 0;
    width: 50rpx;
    height: 50rpx;
    margin-left: 20rpx;
  }

  .list-data-del {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100rpx;
    height: 100%;
    margin-right: 20rpx;
    font-size: 28rpx;
    color: #ffffff;
    border-radius: 10rpx;
    background-color: #ff4d42;
  }
}

.list-no-data {
  height: calc(100vh - env(safe-area-inset-bottom));
}

.list-fixed {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 106rpx;
  padding: 14rpx 60rpx env(safe-area-inset-bottom);
  background-color: #ffffff;
}
</style>